import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/stu")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Connection conn = JdbcUtil.getConnection();
            String sql = "SELECT * FROM classmates ORDER BY id";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();

            List<Student> studentList = new ArrayList<>();

            while (rs.next()) {
                Student student = new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setNickn(rs.getString("nickn"));
                student.setAst(rs.getString("ast"));
                student.setCon(rs.getString("con"));
                student.setImp(rs.getString("imp"));
                studentList.add(student);
            }

            req.setAttribute("students", studentList);
            req.getRequestDispatcher("/student.jsp").forward(req, resp);

        } catch (SQLException e) {
            throw new ServletException("数据库操作失败", e);
        }
    }
}